package com.life.muyu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.life.muyu.dto.AccessTokenDTO;
import com.life.muyu.dto.GithubUser;
import com.life.muyu.dto.ResultDTO;
import com.life.muyu.exception.CustomizeErrorCode;
import com.life.muyu.exception.CustomizeExcetpion;
import com.life.muyu.mapper.UserMapper;
import com.life.muyu.model.User;
import com.life.muyu.provider.GithubProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletResponse;

@Controller
public class AuthorizeController {

    @Autowired
    private GithubProvider githubProvider;

    @Autowired
    private UserMapper userMapper;

    @Value("${github.client.id}")
    private String Client_id;

    @Value("${github.client.secret}")
    private String Client_secrect;

    @Value("${github.redirect.uri}")
    private String Redirect_uri;

    @PostMapping("/getGithubUrl")
    @ResponseBody
    public Object getGithubUrl(){
//        @{https://github.com/login/oauth/authorize(client_id='cd10d2effd964ffb0af2',redirect_uri=${#httpServletRequest.getServletContext().getAttribute('redirectUri')},scope='user',state=1)}"
        StringBuffer uri = new StringBuffer()
                .append("https://github.com/login/oauth/authorize")
                .append("?").append("client_id=").append(Client_id)
                .append("&").append("redirect_uri=").append(Redirect_uri)
                .append("&").append("scope=user")
                .append("&").append("state=1");
        return ResultDTO.okof(uri);
    }

    @GetMapping("/callback")
    public String getCode(@RequestParam(name = "code") String code,
                          @RequestParam(name = "state") String state,
                          HttpServletResponse response,
                          Model model) throws CustomizeExcetpion {
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setClient_id(Client_id);
        accessTokenDTO.setClient_secret(Client_secrect);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(Redirect_uri);
        accessTokenDTO.setState(state);
        String accessToken = githubProvider.getAccessToken(accessTokenDTO);
        GithubUser githubUser = githubProvider.getUser(accessToken);
        if (githubUser==null){
            model.addAttribute("error",CustomizeErrorCode.ACCESS_ERROR);
            return "error";
        }
//        根据githubUser的id去数据库中找到User，如果找到说明是授权的用户，如果没有记录，则代表非授权管理员
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("github_id", githubUser.getId()));
        if (user==null){
            model.addAttribute("error",CustomizeErrorCode.ACCESS_ADMIN_ERROR);
            return "error";
        }
//      如果是管理员登陆，则去更新用户的信息到数据库中
        user.setName(githubUser.getName());
        user.setGithubAvatarUrl(githubUser.getAvatar_Url());
        user.setGithubBio(githubUser.getBio());
        userMapper.updateById(user);
//        登陆成功，跳转到管理员页面
        return "admin/index";
    }
}
